use std::collections::HashMap;
use std::sync::{Arc, RwLock};
use std::any::Any;
use crate::business::service::role_service::RoleService;
use crate::business::service::user_service::UserService;

// 定义一个结构体来保存所有服务实例
#[derive(Clone, Debug)]
pub struct AppContextBeans {
    services: Arc<RwLock<HashMap<String, Arc<dyn Any + Send + Sync>>>>,
}

impl AppContextBeans {
    pub fn new() -> Self {
        AppContextBeans {
            services: Arc::new(RwLock::new(HashMap::new())),
        }
    }

    // 添加Beans实例，样例如下：
    // let app_ctx_beans = AppContextBeans::new();
    // app_ctx_beans.add_bean("user_service", Arc::new(UserService::new(pool.clone())));
    // app_ctx_beans.add_bean("role_service", Arc::new(RoleService::new(pool.clone())));
    pub fn add_bean<T: 'static + Send + Sync>(&self, name: &str, service: Arc<T>) {
        let mut services = self.services.write().unwrap();
        services.insert(name.to_string(), service as Arc<dyn Any + Send + Sync>);
        log::info!("Added bean: {}", name);
    }

    // 批量添加Beans实例，样例如下：
    // let app_ctx_beans = AppContextBeans::new();
    // app_ctx_beans.add_beans(vec![
    //     ("user_service", Arc::new(UserService::new(pool.clone())) as Arc<dyn Any + Send + Sync>),
    //     ("role_service", Arc::new(RoleService::new(pool.clone())) as Arc<dyn Any + Send + Sync>)
    // ]);
    pub fn add_beans(&self, services: Vec<(&str, Arc<dyn Any + Send + Sync>)>) {
        let mut context_services = self.services.write().unwrap();
        for (name, service) in services {
            context_services.insert(name.to_string(), service);
            log::info!("Added bean: {}", name);
        }
    }

    pub fn get_bean<T: 'static + Send + Sync>(&self, name: &str) -> Result<Arc<T>, String> {
        let services = self.services.read().unwrap();
        match services.get(name) {
            Some(service) => {
                match service.clone().downcast::<T>() {
                    Ok(service) => Ok(service),
                    Err(_) => {
                        let error_msg = format!("Service type mismatch for bean: {}", name);
                        log::error!("{}", error_msg);
                        Err(error_msg)
                    }
                }
            },
            None => {
                let error_msg = format!("No service found for bean: {}", name);
                log::error!("{}", error_msg);
                Err(error_msg)
            }
        }
    }
}